﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Expect.Core.Reports;
using System.IO;

namespace Expect.Core.IO
{
    /// <summary>
    /// Parser for text report metadata
    /// </summary>
    public class TextReportMetadataReader
    {
        private ReportMetadataBase _metadata;

        /// <summary>
        /// Parser constructor
        /// </summary>
        /// <param name="metadata"></param>
        public TextReportMetadataReader(ReportMetadataBase metadata)
        {
            _metadata = metadata;
        }

        /// <summary>
        /// Parse report metadata from string
        /// </summary>
        /// <param name="content"></param>
        public void ReadReportMetadata(string content)
        {
            using (StringReader reader = new StringReader(content))
            {
                InnerReadMetadata(reader);
            }
        }

        /// <summary>
        /// Parse report metadata from stream
        /// </summary>
        /// <param name="strm"></param>
        public void ReadReportMetadata(Stream strm)
        {
            using (StreamReader reader = new StreamReader(strm))
            {
                InnerReadMetadata(reader);
            }
        }

        private void InnerReadMetadata(TextReader reader)
        {
            string line = null;
            while ((line = reader.ReadLine()) != null)
            {
                ProcessLine(line.Trim());
            }
        }

        private void ProcessLine(string line)
        {
            if (line.StartsWith("#") || string.IsNullOrEmpty(line)) return;

            if (line.StartsWith("[") && line.EndsWith("]"))
            {
                line = line.Substring(1, line.Length - 2);
                _metadata.AddFolder(line);
                return;
            }

            _metadata.AddFile(line);
        }
    }
}
